<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElTree, ElLoading } from 'element-plus'
import yspglService from '@/api/yspgl'
import TreeUtilDTO from '@/utils/tree'
import { useRoute } from 'vue-router'
import addDialog from '@/views/gdgl/gdzl/ysp/dialogs/add-dialog.vue'
import addPhotoDialog from '@/views/gdgl/gdzl/ysp/dialogs/add-photo-dialog.vue'
import { useMainStore } from '@/store/main'
const store = useMainStore()
const emit = defineEmits(['nodeClick'])
const route = useRoute()
//获取ref
const addDialogRef = ref()
const addPhotoRef = ref()

// 入参
const filterForm = ref({
  gjzValue: '',
})

// 生命周期
// onMounted(() => {
//   // 查询树
//   queryTree()
// })

const init = () => {
  // 查询树
  queryTree()
}

const treeData = ref<any>([])
const treeRef = ref<InstanceType<typeof ElTree>>()
const firtsNode = ref<any>()
/*
 * 查询树
 */
const queryTree = () => {
  //处理数据
  const params = {
    ajmc: route.query.ajmc as unknown as string,
    ajbh: route.query.ajbh as unknown as string,
  }
  yspglService
    .querySxmls(params)
    .then((res) => {
      let obj = route.query
      res.data.forEach((item: any) => {
        if (!item.fbh) {
          item['fbh'] = obj.ajbh
        }
      })
      //处理数据
      res.data.push({
        ajbh: obj.ajbh,
        bh: obj.ajbh,
        mc: obj.ajmc,
        wjsl: 0,
      })
      treeData.value = TreeUtilDTO.getTreeData(res.data, 'bh', 'fbh')
      treeData.value?.forEach((data: any) => {
        if (data.children && data.children.length > 0) {
          data.children.forEach((data1: any) => {
            data.wjsl += data1.wjsl
          })
        }
      })

      if (treeData.value.length) {
        firtsNode.value = null
        // 递归选择第一个
        getFirstNode(treeData.value)
        // 递归添加目录顺序号
        getSxhNode(treeData.value)
        if (firtsNode.value) {
          handleCheckNode(firtsNode.value)
        }
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

const getFirstNode = (arr: any[]) => {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].children && arr[i].children.length > 0) {
      getFirstNode(arr[i].children)
    } else {
      firtsNode.value = arr[i]
    }
    return
  }
}

const getSxhNode = (arr: any[]) => {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].children && arr[i].children.length > 0) {
      getFirstNode(arr[i].children)
    } else {
      arr[i].mlsxh = arr[i]
    }
  }
}

const handleCheckNode = (node: any) => {
  treeNodeClick(node)
  nextTick(() => {
    treeRef.value!.setCurrentKey(node.bh)
  })
}

// 文字过滤
const filterTree = () => {
  treeRef.value?.filter(filterForm.value.gjzValue)
}

/**
 * 树节点过滤
 */
const filterNode = (value: any, data: any) => {
  let flag = true
  if (value) {
    if (typeof value === 'string') {
      // 文字过滤
      flag = data[defaultProps.label].indexOf(value) !== -1
    }
  }
  return flag
}

/*
 * 树节点点击（抛出方法到主界面）
 */
const treeNodeData = ref()

const treeNodeClick = (data: any) => {
  treeNodeData.value = data
  emit('nodeClick', treeNodeData.value)
  mlClose()
}

/* 树选择 */
const menuShow = ref(false)
const rightMenu = ref({
  top: '',
  left: '',
})

/* 目录列表 */
const menuList = ref([
  { text: '添加目录', disabled: true },
  { text: '删除目录', disabled: true },
])

/* 获取节点信息 */
const nodeData = ref<any>([])
/* 树右键点击 */
const rightClick = (e: any, data: any, node: any) => {
  nodeData.value = data //节点信息保存,用于删除卷
  //如果是卷节点,将该节点的下的	文件编号赋值
  if (!nodeData.value?.wjbhList) {
    nodeData.value.wjbhList = []
  }
  for (let i = 0; i < treeData.value.length; i++) {
    if (treeData.value[i].bh === data.bh) {
      for (let j = 0; j < treeData.value[i].children.length; j++) {
        nodeData.value.wjbhList.push(treeData.value[i].children[j].bh)
      }
      break
    }
  }

  //打开按钮目录
  menuShow.value = false // 先把模态框关死，目的是 第二次或者第n次右键鼠标的时候 它默认的是true
  menuShow.value = true
  e.preventDefault() //关闭浏览器右键默认事件
  rightMenu.value = { top: e.pageY + 'px', left: e.pageX + 'px' }
  document.addEventListener('click', (ev) => {
    // ev.stopImmediatePropagation()
    if (ev.target !== document.querySelector('.el-menu-item.is-active')) {
      mlClose()
    }
  })
  if (!data.fbh) {
    menuList.value = [
      { text: '添加目录', disabled: true },
      { text: '删除目录', disabled: true },
    ]
  } else {
    if (data.cj === 1) {
      menuList.value = [
        { text: '添加目录', disabled: false },
        { text: '删除目录', disabled: true },
      ]
    } else {
      menuList.value = [
        { text: '添加目录', disabled: true },
        { text: '删除目录', disabled: false },
      ]
    }
  }
}

/* 关闭目录 */
const mlClose = () => {
  // 取消鼠标监听事件 菜单栏
  menuShow.value = false
  document.removeEventListener('click', mlClose) // 关掉监听，
}

/*
 * 拖拽节点
 */
const handleDrop = (draggingNode: Node, dropNode: Node) => {
  console.log(draggingNode, '被拖拽节点的数据')
  console.log(dropNode, '最后进入的节点')
  const params = {}
  // wsjzglService
  //   .updateMlgs(params)
  //   .then((res) => {
  //     //
  //   })
  //   .catch((err) => {
  //     !err.isError && ElMessage({ type: 'warning', message: err.message })
  //     console.log(err)
  //   })
}

const defaultProps = {
  children: 'children',
  label: 'mc',
}
/* 目录列表点击 */
const menuButton = (e: any) => {
  if (e.text === '添加目录') {
    openAddJDialog(nodeData.value)
  } else if (e.text === '删除目录') {
    deleteAjml(nodeData.value)
  }
}

/*
 * 打开添加目录弹框
 */
const openAddJDialog = (node: any) => {
  if (node.bh === 'gd0020002' || node.bh === 'gd0020001') {
    // 打开音视频目录弹窗
    addDialogRef.value.openDialog(node)
  } else {
    // 打开图片目录弹窗
    addPhotoRef.value.openDialog(node)
  }
}

/*
 * 删除案件目录
 */
const deleteAjml = (e: any) => {
  ElMessageBox.confirm('此操作将永久删除该数据，是否继续?', '提示', {
    cancelButtonText: '取消',
    confirmButtonText: '确定',
    type: 'warning',
  }).then(() => {
    const params = {
      dabh: e.dabh,
      sxmlbh: e.bh,
    }
    yspglService
      .deleteSxml(params)
      .then(() => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        queryTree()
      })
      .catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
  })
}

// 抛出去刷新再请求一次方法
const againTreeData = () => {
  const params = {
    ajmc: route.query.ajmc as unknown as string,
    ajbh: route.query.ajbh as unknown as string,
  }
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  yspglService
    .querySxmls(params)
    .then((res) => {
      let obj = route.query
      res.data.forEach((item: any) => {
        if (!item.fbh) {
          item['fbh'] = obj.ajbh
        }
      })
      //处理数据
      res.data.push({
        ajbh: obj.ajbh,
        bh: obj.ajbh,
        mc: obj.ajmc,
        wjsl: 0,
      })
      treeData.value = TreeUtilDTO.getTreeData(res.data, 'bh', 'fbh')
      treeData.value?.forEach((data: any) => {
        if (data.children && data.children.length > 0) {
          data.children.forEach((data1: any) => {
            data.wjsl += data1.wjsl
          })
        }
      })
      nextTick(() => {
        treeRef.value!.setCurrentKey(store.$state.nodeTreeData?.bh)
      })
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.close()
    })
}

defineExpose({ init, againTreeData })
</script>
<template>
  <div class="container">
    <div class="center">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-input
            v-model="filterForm.gjzValue"
            autosize=""
            placeholder="请输入查询关键字"
            @change="filterTree"
          >
            <template #suffix>
              <el-icon @click="filterTree" class="el-input__icon"><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
      </el-row>
    </div>
    <div class="bottom">
      <!--         @node-drop="handleDrop"
          :allow-drag="allowDrag"
          :allow-drop="allowDrop" -->
      <el-tree
        ref="treeRef"
        style="max-width: 600px"
        :data="treeData"
        node-key="bh"
        highlight-current
        default-expand-all
        :expand-on-click-node="false"
        :props="defaultProps"
        @node-click="treeNodeClick"
        :filter-node-method="filterNode"
      >
        <template #default="{ data }">
          <div class="custom-tree-node">
            <!-- <el-icon v-if="data.fbh"> <FolderOpened /></el-icon> -->
            <img v-if="!data.fbh" src="/src/assets/images/file-icon.png" alt="" />
            <img v-if="data.cj === 1" src="/src/assets/images/file-icon.png" alt="" />
            <img
              v-if="data.mllxmc === '视频' && data.sfxswj === 'Y'"
              src="/src/assets/images/xssptb.png"
              alt=""
            />
            <img
              v-else-if="data.mllxmc === '视频' && (!data.sfxswj || data.sfxswj === 'N')"
              src="/src/assets/images/xxsptb.png"
              alt=""
            />
            <img
              v-else-if="data.mllxmc === '音频' && data.sfxswj === 'Y'"
              src="/src/assets/images/xsyptb.png"
              alt=""
            />
            <img
              v-else-if="data.mllxmc === '音频' && (!data.sfxswj || data.sfxswj === 'N')"
              src="/src/assets/images/xxyptb.png"
              alt=""
            />
            <img
              v-else-if="data.mllxmc === '照片' && data.sfxswj === 'Y'"
              src="/src/assets/images/xszptb.png"
              alt=""
            />
            <img
              v-else-if="data.mllxmc === '照片' && (!data.sfxswj || data.sfxswj === 'N')"
              src="/src/assets/images/xxzptb.png"
              alt=""
            />
            <!-- <el-icon v-if="data.zrz"> </el-icon> -->
            <span :class="data.cj === 2 ? 'over-title' : ''" :title="data.mc"
              >&nbsp;{{ data.mc }}&nbsp;</span
            >
            <span>({{ data.wjsl }})</span>
          </div>
        </template>
      </el-tree>
      <!-- 树形控件右键组件 -->
      <!-- <div v-show="menuShow" class="tree_rightmenu" :style="{ ...rightMenu }">
          <el-button
            v-for="(item, index) in menuList"
            :key="index"
            type="primary"
            text
            :disabled="item.disabled"
            @click="menuButton(item)"
            >{{ item.text }}</el-button
          >
        </div> -->
    </div>
    <add-dialog ref="addDialogRef" @refresh="queryTree"></add-dialog>
    <add-photo-dialog ref="addPhotoRef" @refresh="queryTree"></add-photo-dialog>
  </div>
</template>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  // padding: 5px;
  .top {
    margin-bottom: 10px;
  }
  .center {
    padding-bottom: 10px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.15);
  }
  .bottom {
    height: calc(100% - 43px);
    overflow-y: auto;
    .tree_rightmenu {
      position: fixed;
      width: 120px;
      border: 1px solid rgba(0, 0, 0, 0.15);
      box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
      z-index: 1000;
      background-color: #fff;
      display: flex;
      flex-direction: column;
      align-items: center;
    }
  }
}
.add-ml {
  width: 100%;
}

.el-input__icon {
  cursor: pointer;
}

.custom-tree-node {
  width: calc(100% - 40px);
  display: flex;
  align-items: center;
  .over-title {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
:deep(.el-tabs .el-tabs__content) {
  height: calc(100% - 40px);
  /* overflow: auto; */
  padding: 0;
}

.el-button + .el-button {
  margin-left: 0;
}
</style>
